﻿//using ServiceStack.Logging;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Security;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using ThinkDev.Logging;

namespace EmoneyWeiXinCommon
{
    public class NetHelper
    {
        public const string ENCODE_GBK = "gbk";
        #region 以GET形式访问一个url
        public static string LoadData(string url, Dictionary<string, string> urlParams)
        {
            return LoadData(url, urlParams, "UTF-8");
        }

        public static string LoadData(string url, Dictionary<string, string> urlParams, string encodname)
        {
            string ret = "";
            if (urlParams != null && urlParams.Count > 0)
            {
                url = url.TrimEnd('?');
                url += "?";
                foreach (string key in urlParams.Keys)
                {
                    url += key + "=" + urlParams[key] + "&";
                }
                url = url.TrimEnd('&');
            }
            ////MyTrace.get().add("NetHelper.begin=[" + url + "]", MyTrace.IMPORTANT);
            try
            {
                HttpWebRequest hwr = (HttpWebRequest)WebRequest.Create(url);
                hwr.Method = "GET";
                hwr.KeepAlive = true; hwr.Timeout = 20000;
                hwr.Accept = "*/*";
                hwr.UserAgent = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; SV1; .NET CLR 1.1.4322; .NET CLR 2.0.50727; .NET CLR 3.0.4506.2152; .NET CLR 3.5.30729)";
                hwr.Headers.Add("Accept-Language", "zh-cn");
                hwr.ServicePoint.Expect100Continue = false;
                HttpWebResponse response = (HttpWebResponse)hwr.GetResponse();
                System.IO.Stream myResponseStreame = response.GetResponseStream();
                System.IO.StreamReader sdr = new System.IO.StreamReader(myResponseStreame, Encoding.GetEncoding(encodname));
                //System.IO.StreamReader sdr = new System.IO.StreamReader(myResponseStreame, Encoding.GetEncoding(Encoding.Default.EncodingName));
                ret = sdr.ReadToEnd().ToString();
                ////MyTrace.get().add("NetHelper.end=[" + ret.Substring(0, ret.Length > 500 ? 500 : ret.Length) + "]", MyTrace.IMPORTANT);
                //MyTrace.get().add("NetHelper.end=[" + ret + "]", MyTrace.IMPORTANT);
                ////LogManager.WeiXinApiLogger.Debug(string.Format("LoadData [url={0}] [ret={1}]", url, ret));
            }
            catch (Exception)
            {
                ////MyTrace.get().add("NetHelper.error=[" + ex.Message + "]", MyTrace.IMPORTANT);
                ////LogManager.WeiXinApiLogger.Error(LogConvert.ParseWebEx(ex), string.Format("LoadData发生异常！[url={0}] [ret={1}]", url, ret));
            }
            return ret;
        }
        #endregion

        #region 以POST形式访问一个url
        public static string LoadDataPost(string url, Dictionary<string, string> urlParams, string paramData, Encoding dataEncode)
        {
            string ret = string.Empty;
            if (urlParams != null && urlParams.Count > 0)
            {
                url = url.TrimEnd('?');
                url += "?";
                foreach (string key in urlParams.Keys)
                {
                    url += key + "=" + urlParams[key] + "&";
                }
                url = url.TrimEnd('&');
            }
            try
            {
                ////MyTrace.get().add("NetHelper.begin=["+url+"]");
                byte[] byteArray = dataEncode.GetBytes(paramData);
                HttpWebRequest webReq = (HttpWebRequest)WebRequest.Create(new Uri(url));
                webReq.Method = "POST";
                webReq.ContentType = "application/x-www-form-urlencoded";
                webReq.ContentLength = byteArray.Length;

                Stream newStream = webReq.GetRequestStream();
                newStream.Write(byteArray, 0, byteArray.Length);
                newStream.Close();
                    
                HttpWebResponse response = (HttpWebResponse)webReq.GetResponse();
                StreamReader sr = new StreamReader(response.GetResponseStream(), dataEncode);
                ret = sr.ReadToEnd();
                sr.Close();
                response.Close();
                newStream.Close();
                ////MyTrace.get().add("NetHelper.end=[" + ret + "]");
                ////LogManager.WeiXinApiLogger.Debug(string.Format("LoadDataPost [url={0}] [ret={1}]", url, ret));
            }
            catch (Exception)
            {
                ////MyTrace.get().add("NetHelper.error=[" + ex.Message + "]");
                ////LogManager.WeiXinApiLogger.Error(LogConvert.ParseWebEx(ex), string.Format("LoadDataPost发生异常！[url={0}] [ret={1}]", url, ret));
            }
            return ret;
        }
        #endregion

        private static X509Certificate2 _cert;
        public static bool hasCert()
        {
            return _cert != null;
        }
        public static void createCert(string _pwd, string t_certpath)
        {
            if (_cert == null)
            {
                //MyTrace.get().debug("NetHelper.createCert");
                ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult);
                //ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3; 
                _cert = new X509Certificate2(t_certpath, _pwd, X509KeyStorageFlags.MachineKeySet);
            }
        }

        private static bool CheckValidationResult(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors)
        {
            // MyTrace.get().debug("SslPolicyErrors", errors.ToString());
            if (errors == SslPolicyErrors.None)
                return true;
            return false;
        }

        public static string LoadDataPostWithCert(string url, Dictionary<string, string> urlParams, string paramData, Encoding dataEncode, string _pwd, string t_certpath)
        {
            //MyTrace.get().debug("NetHelper.LoadDataPostWithCert.begin=[" + url + "]");
            if (!hasCert()) createCert(_pwd, t_certpath);
            // MyTrace.get().add("NetHelper.LoadDataPostWithCert.begin2");
            string ret = string.Empty;
            if (urlParams != null && urlParams.Count > 0)
            {
                url = url.TrimEnd('?');
                url += "?";
                foreach (string key in urlParams.Keys)
                {
                    url += key + "=" + urlParams[key] + "&";
                }
                url = url.TrimEnd('&');
            }
            try
            {
                //MyTrace.get().debug("NetHelper.LoadDataPostWithCert.begin21");
                byte[] byteArray = dataEncode.GetBytes(paramData);
                HttpWebRequest webReq = (HttpWebRequest)WebRequest.Create(new Uri(url));
                webReq.Method = "POST";
                webReq.ServicePoint.Expect100Continue = false;
                //MyTrace.get().debug("NetHelper.LoadDataPostWithCert.begin3");
                //ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult);
                //webReq.ClientCertificates.Add(new X509Certificate2(t_certpath, _pwd, X509KeyStorageFlags.MachineKeySet));
                webReq.ClientCertificates.Add(_cert);

                //MyTrace.get().debug("NetHelper.LoadDataPostWithCert.begin4");
                webReq.ContentType = "application/x-www-form-urlencoded";
                webReq.ContentLength = byteArray.Length;

                //MyTrace.get().debug("NetHelper.LoadDataPostWithCert.begin5");
                webReq.Proxy = null;
                webReq.AllowAutoRedirect = true;
                //webReq.KeepAlive = true;
                Stream newStream = webReq.GetRequestStream();
                //MyTrace.get().debug("NetHelper.LoadDataPostWithCert.begin52");
                newStream.Write(byteArray, 0, byteArray.Length);
                //MyTrace.get().debug("NetHelper.LoadDataPostWithCert.begin53");
                newStream.Close();
                //MyTrace.get().debug("NetHelper.LoadDataPostWithCert.begin6=[" + url + "]");
                HttpWebResponse response = (HttpWebResponse)webReq.GetResponse();
                //MyTrace.get().debug("NetHelper.LoadDataPostWithCert.begin7");
                StreamReader sr = new StreamReader(response.GetResponseStream(), dataEncode);
                ret = sr.ReadToEnd();
                sr.Close();
                response.Close();
                newStream.Close();

                //LogManager.WeiXinApiLogger.Debug(string.Format("LoadDataPost [url={0}] [ret={1}]", url, ret));
            }
            catch (Exception ex)
            {

                MyTrace.get().debug("发送红包请求：" + ex.Message);
                //LogManager.WeiXinApiLogger.Error(LogConvert.ParseWebEx(ex), string.Format("LoadDataPost发生异常！[url={0}] [ret={1}]", url, ret));
            }
            return ret;
        }

        //public static T InvokeWebapi<T>(string funname, string paramlist) 
        //{
        //    return InvokeWebapi<T>(funname, paramlist, Config.WeiXin_webapi_appid, Config.WeiXin_webapi_key);
        //}
        //public static T InvokeWebapi<T>(string funname, string paramlist,string appid,string appkey)
        //{
        //    string url = string.Concat(Config.WeiXin_webapi_url, funname + "?appid=", appid);
        //    url = url + paramlist;
        //    url = WebApiHelper.CreateUrl(url, appkey);
        //    string result = NetHelper.LoadData(url, null);
        //    return Newtonsoft.Json.JsonConvert.DeserializeObject<T>(result);
        //}
    }
}
